package com.mogujie.tt.utils;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.util.Map;
import java.util.Set;

/**
 * Created by user on 2015/9/11.
 */
public class HttpUtilsApache {

    public static final String HTTP_404="连接服务器失败";
    public static final String HTTP_500="连接服务器失败";
    public static final String HTTP_900="连接服务器失败";
    public static final String HTTP_901="连接超时";
    public static final String HTTP_902="连接超时";
    public static final String HTTP_903="无法连接服务器，请查看是否正确设置服务器配置";
    public static final String HTTP_904="未找到安全证书";
    public static final String HTTP_UNKONW="未知的错误";
    private static int timeOut=40000;//超时时间

    /**
     *
     * @param url
     * @param jsonObject
     * @return
     */
    public static String usHttpPostJson( String url, JSONObject jsonObject){

        String result = "";
        HttpClient httpclient=null;
        try {

            HttpParams httpParams = new BasicHttpParams();
            // 请求超时
            HttpConnectionParams.setConnectionTimeout(httpParams, timeOut);
            // 读取超时
            HttpConnectionParams.setSoTimeout(httpParams, timeOut);

            // 新建HttpClient对象
            //使用DefaultHttpClient类的execute方法发送HTTP POST请求，并返回HttpResponse对象。
            httpclient = new DefaultHttpClient(httpParams);


            HttpPost httppost = new HttpPost(url);//请求地址
            httppost.addHeader("Content-Type", "application/json");//加入头

            httppost.setEntity(new StringEntity(jsonObject.toString(), HTTP.UTF_8));//设置请求参数

            HttpResponse response = httpclient.execute(httppost);//execute方法发送HTTP

            //result = showResponseResult(response);
            int code = response.getStatusLine().getStatusCode(); // HTTP显示响应
            if (null != response && code == HttpStatus.SC_OK) {

                HttpEntity httpEntity = response.getEntity();//取出应答(得到实体)

                InputStream inputStream = httpEntity.getContent();//得到对于的输入流

                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));//流转换为字节

                String line = "";
                while (null != (line = reader.readLine())) {
                    result += line;
                }

            }else if (code == 404) {
                result = "404";
            } else if (code == 500) {
                result = "500";
            }

        } catch (ClientProtocolException e) {
            result = "900";
        } catch (ConnectTimeoutException e) {
            result = "901";
        } catch (InterruptedIOException e) {
            result = "902";
        } catch (IOException e) {
            result = "903";
        } catch (Exception e) {
            result = "904";
        } finally {
            httpclient.getConnectionManager().shutdown();//HttpClient的实例不再需要时，可以使用连接管理器关闭
        }

        return result;
    }

    /**
     * 错误信息的返回
     *
     * @param jsonstr
     * @return
     */
    public static String errorMsg(String jsonstr) {
        String newMessageInfo = "";

        if ("404".equals(jsonstr)) {
            newMessageInfo = HttpUtilsApache.HTTP_404;
        } else if ("500".equals(jsonstr)) {
            newMessageInfo = HttpUtilsApache.HTTP_500;
        } else if ("900".equals(jsonstr)) {
            newMessageInfo = HttpUtilsApache.HTTP_900;
        } else if ("901".equals(jsonstr)) {
            newMessageInfo = HttpUtilsApache.HTTP_901;
        } else if ("902".equals(jsonstr)) {
            newMessageInfo = HttpUtilsApache.HTTP_902;
        } else if ("903".equals(jsonstr)) {
            newMessageInfo = HttpUtilsApache.HTTP_903;
        }

        return newMessageInfo;
    }


    /**
     * @Description 使用get方式请求
     * @param url
     *            请求地址: http:192.168.1.2:8080/servelt/get
     * @param params
     *            请求的参数数据
     */
    public String usHttpGet(String url, Map<String, Object> params) {
        String result = "";
        if (!params.isEmpty()) {
            Set<String> keyset = params.keySet();
            int i = 0;
            for (String key : keyset) {
                String value = params.get(key).toString();
                if (i == 0) {
                    url = url + "?" + key + "=" + value;
                } else {
                    url += "&" + key + "=" + value;
                }
                i++;
            }
        }
        HttpClient httpClient = null;
        System.out.println("-->请求url:" + url);
        try {
            // 生成请求对象
            HttpGet httpGet = new HttpGet(url);
            HttpParams httpParams = new BasicHttpParams();
            // 请求超时
            HttpConnectionParams.setConnectionTimeout(httpParams, timeOut);
            // 读取超时
            HttpConnectionParams.setSoTimeout(httpParams, timeOut);
            // 新建HttpClient对象
            httpClient = new DefaultHttpClient(httpParams);

            // 发送请求
            HttpResponse response;

            response = httpClient.execute(httpGet);
            // 显示响应
            // result = showResponseResult(response);

            int code = response.getStatusLine().getStatusCode();
            if (null != response && code == HttpStatus.SC_OK) {

                HttpEntity httpEntity = response.getEntity();
                InputStream inputStream = httpEntity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

                String line = "";
                while (null != (line = reader.readLine())) {
                    result += line;
                }

                if(result.indexOf("404 NOT FOUND!")>0){
                    result = "404";
                }

            } else if (code == 404) {
                result = "404";
            } else if (code == 500) {
                result = "500";
            }

        } catch (ClientProtocolException e) {
            result = "900";
        } catch (ConnectTimeoutException e) {
            result = "901";
        } catch (InterruptedIOException e) {
            result = "902";
        } catch (IOException e) {
            result = "903";
            System.out.println(e.getMessage());
        }finally {
            httpClient.getConnectionManager().shutdown();
        }
        return result;
    }


}
